package com.net.framework.help.httprequest.encryptconverter;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;


/**
 * Author：xiaobin.zhang
 * Email：154722566@qq.com
 * Date：2016/8/11 9:29
 * Desc：<--加密-->
 */
public class JsonEncryptConverterFactory extends Converter.Factory {
    private static String key = null;

    /**
     * Create an instance using a default {@link Gson} instance for conversion. Encoding to JSON and
     * decoding from JSON (when no charset is specified by a header) will use UTF-8.
     */
    public static JsonEncryptConverterFactory create(String key) {
        JsonEncryptConverterFactory.key = key;
        return create(new Gson());
    }

    /**
     * Create an instance using {@code gson} for conversion. Encoding to JSON and
     * decoding from JSON (when no charset is specified by a header) will use UTF-8.
     */
    public static JsonEncryptConverterFactory create(Gson gson) {
        return new JsonEncryptConverterFactory(gson);
    }

    private final Gson gson;

    private JsonEncryptConverterFactory(Gson gson) {
        if (gson == null) throw new NullPointerException("gson == null");
        this.gson = gson;
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new JsonEncryptResponseBodyConverter<>(gson, adapter, JsonEncryptConverterFactory.key);
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new JsonEncryptRequestBodyConverter<>(gson, adapter, JsonEncryptConverterFactory.key);
    }
}
